const net = require("net");
const path = require("path");
const fs = require("fs");
const express = require("express");
const ws = require("ws");

// 全局变量
let CLIENTS = [];
const ServerIP = "192.168.137.1";
const ServerPort = 8000;
let IMG;//存储图片数据
// 全局函数
// 发送图片给所有客户端
function sendIMGToClients() {
    for (let i = 0; i < CLIENTS.length; i++) {
        CLIENTS[i].send(IMG);
    }
}

// 创建服务器实例
const app = net.createServer();


//监听端口
app.listen(ServerPort, ServerIP);

app.on("close", () => {
    console.log("服务器关闭!");
});


let recFlag = 0;//记录接收状态
let IMG_PATH = path.join(__dirname, "public", "stream.jpg");//图片保存路径
app.on("connection", (socket) => {
    console.log("新连接!");
    // console.log(socket);
    socket.on("data", (data) => {
        // console.log("收到数据!");
        // 合并数据包
        if (recFlag == 0 && data[0] == 0xFF && data[1] == 0xD8) {
            // console.log("数据头!");
            recFlag = 1;
            IMG = new Uint8Array();
        }
        if (recFlag == 0) return;
        // 拼接
        let temp = new Uint8Array(IMG.length + data.length);
        temp.set(IMG);
        temp.set(data, IMG.length);
        IMG = new Uint8Array(temp);
        if (data[data.length - 2] == 0xFF && data[data.length - 1] == 0xD9) {
            // 把图片写入本地
            fs.writeFile(IMG_PATH, IMG, "binary", (err) => {
                if (err) {
                    console.log("文件保存失败!");
                }
            });
            console.log("new IMG!" + Date());
            // 发送图片给所有客户端
            sendIMGToClients();
            recFlag = 0;
        }
    });
});
app.on("listening", () => {
    console.log("TCP服务器正在监听:" + ServerIP + ":" + ServerPort);
});

// 创建WebServer
const web = express();
web.use(express.static("public"));
// 监听端口
web.listen(80, () => {
    console.log("WEB服务器:" + ServerIP + ":80");
});



// 创建websocket服务器
const socketServer = new ws.WebSocketServer({ port: 81 });
socketServer.on("listening", () => {
    console.log("webSocket服务器:" + ServerIP + ":81");
});

// 判断ID是否唯一
function isIdOnly(id) {
    for (let i = 0; i < CLIENTS.length; i++) {
        if (CLIENTS[i].id == id) {
            return false;
        }
    }
    return true;
}
// 通过ID删除队列中的元素
function delClientByID(id) {
    for (let i = 0; i < CLIENTS.length; i++) {
        if (CLIENTS[i].id == id) {
            CLIENTS.splice(i, 1);
            return;
        }
    }
}
socketServer.on("connection", (socket) => {
    socket.on("message", (data, isBinart) => {
        console.log("来自客户端:" + data);
    });
    socket.on("close", (code, reason) => {
        console.log("客户端断开连接!");
        delClientByID(socket.id);
        console.log("当前客户端连接数:" + CLIENTS.length);
    });
    // 给socket赋予一个唯一ID
    let id;
    do {
        id = Math.random();
    } while (!isIdOnly(id));
    socket.id = id;
    // 添加到队列里
    CLIENTS.push(socket);
    console.log("当前客户端连接数:" + CLIENTS.length);
});